package com.jpress.filtro;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.jpress.beans.SessaoBean;

//@WebFilter("/*")
public class LoginFilter implements Filter {

	public LoginFilter() {}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		SessaoBean sessaoBean = (SessaoBean) req.getSession().getAttribute("SessaoBean");

		if (req.getServletPath().toLowerCase().contains("javax.faces.resource")
				|| req.getServletPath().contains("resources")) {
			chain.doFilter(request, response);
			return;
		}

		if (!req.getServletPath().equals("/index.jsf")) {
			if (sessaoBean == null || !sessaoBean.isAutenticado()) {
				if(req.getServletPath().contains("blog")){
					chain.doFilter(request, response);
				}
				req.getRequestDispatcher("/index.jsf").forward(request,	response);
			}
			
			if(req.getServletPath().contains("administracao") && !sessaoBean.getUsuarioAutenticado().isAdmin()){
				req.getRequestDispatcher("/index.jsf").forward(request,	response);
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {}

}
